import { createRouter, createWebHistory } from "vue-router"

//导入组件
import LoginVue from '@/views/Login.vue'
import LayoutVue from '@/views/Layout.vue'//主页面框架组件

//文章子组件
import ArticleCategoryVue from "@/views/article/ArticleCategory.vue"
import ArticleManageVue from "@/views/article/ArticleManage.vue"
//用户子组件
import UserInfoVue from "@/views/user/UserInfo.vue"
import UserAvatarVue from "@/views/user/UserAvatar.vue"
import UserResetPasswordVue from "@/views/user/UserResetPassword.vue"
import UserMessageVue from "@/views/user/UserMessage.vue"

//权限控制子组件
import PrivilegesManageVue from "@/views/privileges/PrivilegesManage.vue"
import PrivilegesApplyVue from "@/views/privileges/PrivilegesApply.vue"
import PrivilegesVerifyVue from "@/views/privileges/PrivilegesVerify.vue"
//冷库状态管理子组件
import ColdStorageManageVue from "@/views/coldStorage/ColdStorageManage.vue"
import ColdStorageSensorVue from "@/views/coldStorage/ColdStorageSensor.vue"
import ColdStorageUseVue from "@/views/coldStorage/ColdStorageUse.vue"
import { ref } from "vue"

//定义路由关系
let routes = [
    { path: '/login', component: LoginVue },
    {
        path: '/', component: LayoutVue, redirect: '/user/info',//默认的重定向
        children: [
            { path: '/article/category', component: ArticleCategoryVue/*, meta: { role: roles.value.map(role => role.role) } */},
            { path: '/article/manage', component: ArticleManageVue},

            { path: '/user/info', component: UserInfoVue},
            { path: '/user/avatar', component: UserAvatarVue},
            { path: '/user/resetPassword', component: UserResetPasswordVue,},
            { path: '/user/message', component: UserMessageVue},
            { path: '/privileges/manage', component: PrivilegesManageVue},
            { path: '/privileges/apply', component: PrivilegesApplyVue},
            { path: '/privileges/verify', component: PrivilegesVerifyVue},
            { path: '/coldstorage/construct', component: ColdStorageManageVue},
            { path: '/coldstorage/sensor', component: ColdStorageSensorVue },
            { path: '/coldstorage/use', component: ColdStorageUseVue }
        ]
    }
]

//创建路由器
const router = createRouter({
    history: createWebHistory(),
    routes: routes
})

import useUserInfoStore from "@/stores/userInfo.js";
import useSystemParameter from "@/stores/useSystemParameter"
import { ElMessage } from "element-plus"
import { useTokenStore } from "@/stores/token"
// 导航守卫，用于检查用户角色，注意在这之前还会有请求拦截器request.js，
router.beforeEach(async (to, from, next) => {
    const systemPatameter = useSystemParameter();
    //访问登录页面
    //1缓存处理
    if (to.path === '/login') {
        // const systemPatameter = useSystemParameter();无效修改
        // roles.value = systemPatameter.roles;//从缓存拿出权限集合

        next();
    } else {//登录以外的页面，根据缓存的role检查权限是否符合要求
        const userInfoStore = useUserInfoStore()//在这之前要app.use(pinia)，所以这个东西必须放在方法内

        //更新缓存用户信息（主要为了刷新权限，以根据权限表判断访问）
        await userInfoStore.renewInfo();//当未登录直接请求时，会在这里出错。。。request.js拦截401到/login。。。。。。。。。。。。。再到请先登录。。。。。。。。。。。。。。

        //2转发处理
        const CurrentUserRole = systemPatameter.getCurrentUserRole();
        console.log(to.path);
        console.log(CurrentUserRole[to.path]);
        // if (userInfoStore.info.role === 'freeze') {//能被请求拦截器拦截，不必要了
        //     userInfoStore.removeInfo();//清空缓存
        //     const tokenStore = useTokenStore();
        //     tokenStore.removeToken();//清空token
        //     next({ path: '/login' })
        //     ElMessage.error("账号被冻结，请申请解冻，或联系系统管理员_index.js")
        // }
        if (CurrentUserRole[to.path] !== 1) {//不符合权限要求，遣返
            // console.log(userInfoStore.info.role)
            next({ path: from.path });//拦截到来源页
            ElMessage.error('您不具备权限')
        }
        else if (userInfoStore.info.role !== 'freeze') {//符合要求
            //未读消息数计算
            userInfoStore.countUnread();
            next(); //放行
        }
        // else {
        //     ElMessage.error("没考虑到呢给你送到login吧，index.js142")
        //     userInfoStore.removeInfo();//清空缓存
        //     const tokenStore = useTokenStore();
        //     tokenStore.removeToken();//清空token
        //     next();
        // }

    }
});


//导出路由
export default router



